import React, { useState, useEffect } from "react";
import { connect } from "react-redux";
import NavHeader from "@/components/NavHeader";
import { Skeleton, Card, Button, Alert, message } from "antd";
import { Link } from "react-router-dom";
import Dog, { DogResult } from "@/typings/dog";
import actions from "@/store/actions/cart";

import "./index.less";
import { getDog } from "@/api/home";

const Detail = (props: any) => {
  let [dog, setDog] = useState({} as Dog);
  useEffect(() => {
    (async () => {
      let dog = props.location.state; // home通过state属性传过来的
      if (!dog) {
        //刷新情况
        let id = props.location.match.params.id;
        try {
          let result = (await getDog(id)) as any;
          if (result.success) dog = result.data;
          else {
            message.error("获取狗详细失败了");
          }
        } catch (e) {
          message.error(e.message);
        }
      }
      setDog(dog);
    })();
  }, []);
  const addCartItem=(dog:Dog)=>{
    let video= document.querySelector("#dog-video") as HTMLVideoElement;
    let cart=document.querySelector(".anticon.anticon-shopping-cart") as HTMLElement;
    let cloneVideo= video.cloneNode(true) as HTMLVideoElement;
    let videoWith= video.offsetWidth;
    let videoHeight=video.offsetHeight;
    let cartWidth=cart.offsetWidth;
    let cartHeight=cart.offsetHeight;
    let {left:videoLeft,top:videoTop}=video.getBoundingClientRect();
    let {right:cartRight,bottom:cartBottom}=cart.getBoundingClientRect();
    cloneVideo.style.cssText=`
    z-index:1000;
    opacity:0.8;
    position:fixed;
    width:${videoWith}px;
    height:${videoHeight}px;
    top:${videoTop}px;
    left:${videoLeft}px;
    transition:all 1s ease-in-out;
    `;
    document.body.appendChild(cloneVideo);
    cloneVideo.src="";
    setTimeout(()=>{
        cloneVideo.style.left= cartRight-cartWidth/2+"px";
        cloneVideo.style.top= cartBottom-cartHeight/2+"px";
        cloneVideo.style.width=`0px`;
        cloneVideo.style.height=`0px`;
        cloneVideo.style.opacity="50";        
    });//保证添加到dom在开始进行动画
    setTimeout(() => {
      cloneVideo.parentNode!.removeChild(cloneVideo);
  }, 1000);
    props.addCartItem(dog);
  }

  return (
    <>
      <NavHeader history={props.history}>狗狗详情</NavHeader>
      <Card
        hoverable
        style={{ width: "100%" }}
        cover={<video id="dog-video" src={dog.video} controls autoPlay={true} muted>您的浏览器不支持 video 标签。</video>}
      >
        <Card.Meta
          title={dog.title}
          description={<>
          <p>价格：{dog.price}</p>
          <p><Button type="primary" className="add-cart" onClick={()=>{addCartItem(dog)}}>
            加入购物车
            </Button></p>
          </>}
        ></Card.Meta>
      </Card>
    </>
  );
};
const mapStateToProps=(state:any)=>state;

export default connect(mapStateToProps,actions)(Detail);
